#include "YGEngine.h"

#include "YGLog.h"

namespace YoghurtGum
{

#ifdef OLDCODE

	bool					Engine::s_Running = false;
	Game*					Engine::s_Game = NULL;

	unsigned long			Engine::s_PhysicsStart;
	unsigned long			Engine::s_PhysicsCurrent;
	float					Engine::s_PhysicsTime;

	#ifdef YG_LOG_FPS

		unsigned long		Engine::start;
		unsigned long		Engine::end;
		int					Engine::counter = 0;

	#endif

	int Engine::SetSetting(Setting a_Setting, const char* a_Value)
	{
		/*switch (a_Setting)
		{
		case YGS_WINDOWTITLE:

		}*/

		return 0;
	}


	void Engine::Init()
	{
		Device::Init();
		Keyboard::Init();

	#ifdef YG_LOG_FPS

		start = YG_TIMER();

	#endif

		s_Running = true;
	}

	void Engine::Tick()
	{
		CheckExit();

		Keyboard::Clear();
		Keyboard::Update();

	#ifdef YG_USE_FIXED_TIMESTEP

		s_PhysicsCurrent = YG_TIMER();
		float delta = (float)(s_PhysicsCurrent - s_PhysicsStart);
		s_PhysicsStart = s_PhysicsCurrent;

		s_PhysicsTime += delta;

		while (s_PhysicsTime > YG_FIXED_TIMESTEP)
		{
			s_Game->Update();

			Render();

			s_PhysicsTime -= YG_FIXED_TIMESTEP;
		}

	#else

		s_Game->Update();

		Render();

	#endif

	#ifdef YG_LOG_FPS

		if (counter++ == 100)
		{
			end = YG_TIMER();
			const float fps = ((float)(end - start) / 100.f);
			Log::GetSingleton() << "Average FPS: " << (1000.f / fps) << "\n";
			start = end;
			counter = 0;
		}

	#endif

	}

	bool Engine::PreRender()
	{
		CheckExit();

		TouchScreen::Clear();
		Keyboard::Clear();
		Keyboard::Update();

		Device::PreRender();

		return true;
	}

	void Engine::Render()
	{
		if (Device::Update())
		{
			Device::Clear();
			Device::PreRender();
			s_Game->Render();
			Device::PostRender(); 
		}
	}

	void Engine::ShutDown()
	{
		Device::CleanUp();
		Log::CleanUp();
	}

#if (YG_OS_TYPE == YG_OS_TYPE_ANDROID)

	void SegmentationHandler(int a_Fault)
	{
		printf("Got it: %d, %x\n", a_Fault, &a_Fault);
	}

#endif


	void Engine::Run()
	{

#if (YG_OS_TYPE == YG_OS_TYPE_ANDROID)

		struct sigaction sa = { 0 };
		struct sigaction oldsa = { 0 };

		sa.sa_flags = SA_RESTART;
		sa.sa_handler = SegmentationHandler;

		if (sigaction(SIGALRM, &sa, &oldsa) < 0)
		{
			perror("sigaction");
			return;
		}

#endif

		s_Game = Game::Create();

		Engine::Init();
		s_Game->Init();

		s_PhysicsStart = YG_TIMER();

		while (Engine::s_Running)
		{
			Engine::Tick();
		}

		Engine::ShutDown();
	}

	void Engine::Quit()
	{
		s_Running = false;
	}

#endif

}; // namespace YoghurtGum